<template>
    <div class="invoice-add">
        <!-- 顶部导航 -->
        <van-nav-bar
            title="新增发票抬头"
            right-text="保存"
            left-arrow
            @click-left="onClickLeft"
            @click-right="onClickRight"
        />

        <!-- form 表单 -->
        <van-form ref="InvoiceFormRef">
            <van-field
                v-model="invoice.name"
                name="name"
                label="抬头名称"
                placeholder="必填，公司名称"
                :rules="[{ required: true, message: '请填写抬头名称' }]"
            />
            <van-field
                v-model="invoice.sno"
                name="sno"
                label="税号"
                placeholder="必填，纳税人识别号"
                :rules="[{ required: true, message: '请填写纳税人识别号' }]"
            />

            <van-field
                v-model="invoice.email"
                name="email"
                label="邮箱"
                placeholder="请填写常用邮箱（选填）"
                :rules="[{ emailValidator, message: '邮箱格式不正确' }]"
            />

            <!-- 增值税专用发票 -->
            <van-field
                name="switch"
                label="需要增值税专用发票"
                label-width="150px"
                input-align="right"
            >
                <template #input>
                    <van-switch v-model="invoice.is_zy" size="20" />
                </template>
            </van-field>

            <!-- 设置为默认发票 -->
            <van-field
                name="switch"
                label="设置为默认发票"
                label-width="150px"
                input-align="right"
            >
                <template #input>
                    <van-switch v-model="invoice.is_default" size="20" />
                </template>
            </van-field>
        </van-form>
    </div>
</template>

<script>
export default {
    data() {
        return {
            invoice: {
                name: '',
                sno: '',
                is_zy: false,
                is_default: false,
            },
        };
    },
    methods: {
        onClickLeft() {
            this.$router.push('/invoice/list');
        },
        onClickRight() {
            console.log('保存');
            this.$refs.InvoiceFormRef.validate().then(
                async () => {
                    console.log(this.invoice);
                    const body = {};
                    const res = await this.$http.post('/invoices');
                    if (res.code !== 201) {
                        // 提示错误信息
                        return;
                    }
                    // 跳转到列表页面
                    this.$router.push('/invoice/list');
                },
                (error) => {
                    console.log('error', error);
                },
            );
        },
        // 校验函数返回 true 表示校验通过，false 表示不通过
        emailValidator(val) {
            return /1\d{10}/.test(val);
        },
    },
};
</script>

<style lang="less" scoped></style>
